package com.enzoism.springboot.util.common.bean;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;


/**
 * 参考网站：https://www.cnblogs.com/dalianpai/p/11679252.html
 */
@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     * 从IOC中获得对象: 根据类型
     */
    public static <T> T getBean(Class<T> requiredType){
        return applicationContext.getBean(requiredType);
    }

    /**
     * 从IOC中获得对象, 自动转型为所赋值对象的类型.
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) applicationContext.getBean(name);
    }

    /**
     * 从IOC中获得多个对象(实现接口或继承的)
     */
    public static <T> Map<String, T> getBeansOfType(Class<T> requiredType){
        return applicationContext.getBeansOfType(requiredType);
    }

    /**
     * 清除SpringContextHolder中的ApplicationContext为Null.
     */
    public static void clearHolder() {
        applicationContext = null;
    }

    /**
     * 核心方法1：setApplicationContext(ApplicationContext applicationContext)
     * 核心方法2：getApplicationContext()
     * 作用：可以方便获得ApplicationContext中的所有bean，可以调取spring容器中管理的各个bean。
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }


}